<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dwg Database JSON Viewer</title>
    <script src="https://cdn.jsdelivr.net/npm/jsoneditor@10.2.0/dist/jsoneditor.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/jsoneditor@10.2.0/dist/jsoneditor.min.css" rel="stylesheet">
    <style>
      #dwgInfo:empty {
        height: 10px;
      }
    
      #dwgInfo {
        margin-top: 10px;
        margin-bottom: 10px;
      }
    </style>
</head>
<body>
    <h1>Dwg Database JSON Viewer</h1>
    <input type="file" id="fileInput" accept=".dwg" />
    <div id="dwgInfo"></div>
    <div id="jsonEditor"></div>
    <script type="module" src="dist/libredwg-web.js" defer></script>
    <script type="module" >
      import { Dwg_File_Type, DwgCodePage, LibreDwg } from './dist/libredwg-web.js'

      // load libredwg webassembly module
      const libredwg = await LibreDwg.create()

      const printDwgInfo = (version, codepage, stats) => {
        const infoElement = document.getElementById('dwgInfo')
        infoElement.innerHTML = ''
        infoElement.textContent = `Version: ${version.hdr}, Code Page: ${DwgCodePage[codepage]}, Unknown Entities: ${stats.unknownEntityCount}`
      }

      // create the editor
      const container = document.getElementById('jsonEditor')
      const options = {
        mode: 'view'
      }
      const editor = new JSONEditor(container, options)
    
      // handle file input change event
      const fileInput = document.getElementById('fileInput')
      fileInput.addEventListener('change', function(event) {
        const file = event.target.files[0]
        if (file) {
          // create a FileReader to read the file
          const reader = new FileReader()

          // define the callback function for when the file is read
          reader.onload = function(e) {
            const fileContent = e.target.result
            try {
              const dwg = libredwg.dwg_read_data(fileContent, Dwg_File_Type.DWG)
              const version = libredwg.dwg_get_version_type(dwg)
              const codepage = libredwg.dwg_get_codepage(dwg)
              const result = libredwg.convertEx(dwg)
              printDwgInfo(version, codepage, result.stats)
              editor.set(result.database)
              libredwg.dwg_free(dwg)
            } catch (error) {
              console.error('Failed to process dwg file: ', error)
            }
          }

          // read the file
          reader.readAsArrayBuffer(file)
        } else {
          console.log('No file selected')
        }
      })
    </script>
</body>
</html>